package com.learn.training.multithread.chapter6.minchapter8.demo1;

import java.util.UUID;
import java.util.concurrent.Semaphore;

public class AccessLimitControl {
    // 任意时刻仅允许最多2个线程获取许可,且时公平锁
    final Semaphore semaphore = new Semaphore(2, true); // 5个许可，公平锁

    public String access(String name) throws InterruptedException {
        // 如果超过了许可数量,其他线程将在此等待:
        System.out.println(Thread.currentThread().getName() + "  is waiting for access");
        semaphore.acquire();
        try {
            String s = Thread.currentThread().getName() + "  get access   " + "   " + UUID.randomUUID();
            System.out.println(s);
            return s;
        }finally {
            semaphore.release();
            System.out.println(Thread.currentThread().getName() + "  release");
        }
    }
}
